const audio = wx.createInnerAudioContext(); 
audio.src = 'https://7072-project-7gj8ok755ee9d729-1333095443.tcb.qcloud.la/audio/5c7357878e338.mp3?sign=376614c4d4ecd118a2e1e7007c7eb72a&t=1736090259'; 

audio.loop = true;

const correct_audio = wx.createInnerAudioContext();
correct_audio.src = 'https://7072-project-7gj8ok755ee9d729-1333095443.tcb.qcloud.la/audio/%E7%94%B5%E5%AD%90%E6%8F%90%E7%A4%BA%E9%9F%B3%E5%8F%AE%E5%92%9A%E6%8A%A2%E7%AD%94%E5%9B%9E%E7%AD%94%E6%AD%A3%E7%A1%AE%E9%9F%B3%E6%95%88_%E7%88%B1%E7%BB%99%E7%BD%91_aigei_com.mp3?sign=13a7747f15a22f6ec124ba64ba456eb1&t=1736091189';

const incorrect_audio = wx.createInnerAudioContext();
incorrect_audio.src = 'https://7072-project-7gj8ok755ee9d729-1333095443.tcb.qcloud.la/audio/%E6%BB%B4%E6%BB%B4%20%E7%B3%BB%E7%BB%9F%E8%AD%A6%E5%91%8A%20%E6%B8%B8%E6%88%8F%20%E5%9B%9E%E7%AD%94%E9%94%99%E8%AF%AF%E6%8F%90%E7%A4%BA%20%20%20%E7%BB%BC%E8%89%BA%E8%8A%82%E7%9B%AE_%E7%88%B1%E7%BB%99%E7%BD%91_aigei_com.mp3?sign=c5f8c843097dc4b34e8c2a479ff40409&t=1736091266';

Page({
  data: {
    questions: [], 
    currentQuestionIndex: 0, 
    selectedOption: '', 
    isCorrect: false, 
    totalQuestions: 10, 
    score: 0, 
    isPlaying: false, 
    rotation: 0,
    quizId: '', 
    answers: [], 
    quizCompleted: false,
    button_status:false,
  },

  onLoad: function (options) {
    const id = options._id; 
    if (id) {
      console.log('接收到的ID:', id); 
      this.setData({ quizId: id }); 
    } else {
      console.error('未接收到ID');
    }
    this.getRandomQuestions(); 
    this.toggleMusic(); 
  },

  look_options:function(){
    wx.navigateTo({
      url: `../answer_record/answer_record?_id=${this.data.quizId}`,
    })
  },

  
  getRandomQuestions: function () {
    const db = wx.cloud.database();
    db.collection('cms-questions').aggregate().sample({ size: 10 }).end({
      success: res => {
        if (res.list.length > 0) {
          this.setData({
            questions: res.list, 
            totalQuestions: res.list.length 
          });
          this.getQuestion(0); 
        }
      },
      fail: err => {
        console.error('获取随机题目失败', err);
      }
    });
  },

  
  getQuestion: function (index) {
    if (this.data.quizCompleted) return;
    const question = this.data.questions[index];
    if (question) {
      this.setData({
        question: question,
        selectedOption: '', 
        isCorrect: false 
      });
    }
  },

  onOptionChange: function (e) {
    if (this.data.quizCompleted) return;
    const selectedOption = e.currentTarget.dataset.option;
    const isCorrect = selectedOption === this.data.question.correctAnswer;
    this.setData({
      selectedOption: selectedOption,
      isCorrect: isCorrect
    });
    if (isCorrect) {
      wx.showToast({
        title: '回答正确',
        icon: 'success'
      });
      correct_audio.play();
      this.setData({
        score: this.data.score + 10
      });
    } else {
      wx.showToast({
        title: '回答错误',
        icon: 'none'
      });
      incorrect_audio.play();
    }

    
    this.submitToDatabase();

    
    setTimeout(() => {
      this.goToNextQuestion();
    }, 1500); 
  },

  
  submitToDatabase: function () {
    const db = wx.cloud.database();
    const answerRecord = {
      question: this.data.question.text, 
      options: this.data.question.options, 
      selectedOption: this.data.selectedOption, 
      correctAnswer: this.data.question.correctAnswer, 
      isCorrect: this.data.isCorrect, 
      score: this.data.score 
    };

    db.collection('answer_record').where({
      _id: this.data.quizId 
    }).update({
      data: {
        answers: db.command.push(answerRecord) 
      },
      success: res => {
        console.log('答案记录更新成功');
      },
      fail: err => {
        console.error('更新答案记录失败', err);
      }
    });
  },

  // 跳转到下一题
  goToNextQuestion: function () {
    if (this.data.currentQuestionIndex < this.data.totalQuestions - 1) {
      this.setData({
        currentQuestionIndex: this.data.currentQuestionIndex + 1
      });
      this.getQuestion(this.data.currentQuestionIndex);
    } else {
      wx.showToast({
        title: '已答完所有题目',
        icon: 'success'
      });
      this.setData({
        quizCompleted: true,
        button_status:true,
      });
      this.finalizeAnswerRecord(); 
    }
  },

  // 更新最终答题记录
  finalizeAnswerRecord: function () {
    const db = wx.cloud.database();
    db.collection('answer_record').where({
      _id: this.data.quizId 
    }).update({
      data: {
        totalScore: this.data.score, 
        totalQuestions: this.data.totalQuestions 
      },
      success: res => {
        console.log('最终答题记录更新成功');
      },
      fail: err => {
        console.error('更新最终答题记录失败', err);
      }
    });
  },

  toggleMusic() {
    if (this.data.isPlaying) {
      audio.pause(); 
      this.setData({ isPlaying: false, rotation: 0 }); 
      clearInterval(this.rotationInterval); 
    } else {
      audio.play(); 
      this.setData({ isPlaying: true });
      this.startRotation(); 
    }
  },

  startRotation() {
    let angle = this.data.rotation; 
    this.rotationInterval = setInterval(() => {
      angle += 10; 
      this.setData({ rotation: angle }); 
    }, 250); 
  },

  onUnload() {
    audio.stop(); 
    clearInterval(this.rotationInterval); 
  }
});
